package exsun.jt808.data.media.operate.Subscriber;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class SubscriberManager<T> {

    private final static Logger logger = LoggerFactory.getLogger(SubscriberManager.class);

    public static SubscriberManager instance = new SubscriberManager();

     private List<Subscriber<T>> _subscribers = new ArrayList<>();

     public void addSubscriber(Subscriber<T> subscriber){
         if(subscriber == null)return;
         synchronized (_subscribers){
             _subscribers.add(subscriber);
         }
         logger.info("新增连接，当前连接数：{}", count());
     }

    public void addSubscriber(String sessionId, T session, String subscriberId, String subscriberType){
        if(sessionId == null||subscriberId == null||subscriberType == null)return;
        Subscriber subscriber = new Subscriber(sessionId, session, subscriberId, subscriberType);
        synchronized (_subscribers){
            _subscribers.add(subscriber);
        }
        logger.info("新增连接：subscriberId:{}，subscriberType: {}, 当前连接数：{}",subscriberId, subscriberType, count());
    }

    public List<Subscriber<T>> getSubscribers(String subscriberId, String subscriberType){
        List<Subscriber<T>> list = _subscribers.stream().filter(x->x.getSubscriberId().equals(subscriberId)
                &&x.getSubscriberType().equals(subscriberType)).collect(Collectors.toList());
        return list;
    }

    public List<Subscriber<T>> getSubscribersBySubType(String subscriberType){
        List<Subscriber<T>> list = _subscribers.stream().filter(x->x.getSubscriberType().equals(subscriberType))
                .collect(Collectors.toList());
        return list;
    }

    public List<Subscriber<T>> getSubscribersBySessionId(String sessionId){
        List<Subscriber<T>> list = _subscribers.stream().filter(x->x.getSessionId().equals(sessionId)
                ).collect(Collectors.toList());
        return list;
    }

    public List<Subscriber<T>> getSubscribers(String subscriberId){
        List<Subscriber<T>> list = _subscribers.stream().filter(x->x.getSubscriberId().equals(subscriberId)
                ).collect(Collectors.toList());
        return list;
    }

    public void remove(String subscriberId, String subscriberType){
        synchronized (_subscribers){
            _subscribers.removeIf(x->x.getSubscriberId().equals(subscriberId)&&x.getSubscriberType().equals(subscriberType));
        }
    }

    public void removeBySubscriberId(String subscriberId){
        synchronized (_subscribers){
            _subscribers.removeIf(x->x.getSubscriberId().equals(subscriberId));
        }
    }

    public void removeBySessionId(String sessionId){
         synchronized (_subscribers){
             _subscribers.removeIf(x->x.getSessionId().equals(sessionId));
         }
    }



    public int count(){
        return _subscribers.size();
    }

}
